import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import ArticleItem from '../ArticleItem'
import { useDispatch } from 'react-redux'
import { getArticleList } from '@/store/actions/home'
import { useSelector } from 'react-redux'
import { PullToRefresh,InfiniteScroll } from 'antd-mobile-v5'
// 不能使用require命名
// import require from '@/utils/request'

export default function ArticleList({ channelId, activeId }) {
	// 是否有更多数据
	const [hasMore, setHasMore] = useState(true)
	const dispatch = useDispatch()
	// 节流, 是否正在加载数据
	const [loading, setLoading] = useState(false)
	const current = useSelector((state) => state.home.articles[channelId])

	useEffect(() => {
		// 如果该频道有数据, 就不需要发送数据
		if (current) return
		if (channelId === activeId) {
			dispatch(getArticleList(channelId, Date.now()))
		}
	}, [channelId, activeId, dispatch, current])

	// 如果不是当前频道, 没有文章数据, 先不渲染
	
	const onRefresh = async () => {
		// 下拉刷新, 需要重新加载最新的数据
		setHasMore(true)
		await dispatch(getArticleList(channelId, Date.now()))
	}

	const loadMore = async () => {
		// setHasMore(false)
		if (loading) return
		// 如果不是当前的频道也不需要加载
		if(channelId !== activeId ) return 
		setLoading(true)

		// 如果没有timestamp, 代表没有数据
		if(!current.timestamp) {
			setHasMore(false)
			setLoading(false)
			return
 		}

		try {
			await dispatch(getArticleList(channelId, current.timestamp), true)
		}finally {
			setLoading(false)
		}
	}

	if (!current) return null
	return (
		<div className={styles.root}>
			<div className="articles">
				<PullToRefresh onRefresh={onRefresh}>
					{current.list.map((item) => (
						<div key={item.art_id} className="article-item">
							<ArticleItem article={item} channelId={channelId}></ArticleItem>
						</div>
					))}
				</PullToRefresh>
				{/* 上拉加载更多 */}
				<InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
			</div>
		</div>
	)
}
